import { Component, Input, OnInit } from '@angular/core';
import { MemberService } from 'src/app/services/member.service';
import { UtilService } from 'src/app/services/util.service';
@Component({
  selector: 'app-member-avatar',
  template: `<img class="lazyload" [defaultImage]="defAvatar" [lazyLoad]="avatarURL" [ngStyle]="scaleSize"/>`
})
export class MemberAvatarComponent implements OnInit {
  @Input()
  public uid: number = 0;
  @Input('scale')
  public scale: number = 32;
  public scaleSize: any = { "width": "32px", "height": "32px" };
  public avatarURL!: string;
  public defAvatar: string = 'assets/avatar/default.png';

  /**
   * 总是取最新的,需要单独的发出请求
   * @param memberService 
   * @param util 
   */
  constructor(private memberService: MemberService, private util: UtilService) { }

  ngOnInit(): void {
    if (this.scale !== 32) {
      this.scaleSize = { "width": this.scale + "px", "height": this.scale + "px" };
    }
    this.getData(this.uid);
  }

  private getData(memberId: number): void {
    const aURL: string | null = this.util.getCacheDecodeMemberAvatar(memberId);
    if (null === aURL) {
      this.memberService.getAvatar(memberId).subscribe(res => {
        this.avatarURL = res;
        this.util.cacheDecodeMemberAvatar(memberId, res);
      });
    } else {
      this.avatarURL = aURL;
    }
  }
}
